package C051;

/**
 * ClassName: C05
 * Package: C051
 * Description:
 *
 * @Author BCXJ
 * @Create 2025/3/10 11:35
 * @Version 1.0
 * @Since 1.0
 */
public class C05 {
    public static void main(String[] args) {
        int[] arr = {10,10,3,5};
        System.out.println(maxRunTime(3, arr));
    }



    public static long maxRunTime(int n, int[] batteries) {
        long sum = 0, max = Integer.MIN_VALUE;
        for (int i = 0; i < batteries.length; i++) {
            sum += batteries[i];
            max = Math.max(max, batteries[i]);
        }

        if(sum >= max * n) {
            return sum / n;
        }


        // 二分
        long l = 0, r = max, mid, ans = 0;
        while(l <= r) {
            mid = l + ((r - l) >> 1);
            if(process(batteries, n, mid)) {
                l = mid + 1;
                ans = mid;
            } else {
                r = mid - 1;
            }
        }
        return ans;
    }


    // arr电池能否为n太电脑 提供 time的时间
    private static boolean process(int[] arr, int n, long time) {
        long sum = 0; // 碎片时间
        for (int i = 0; i < arr.length; i++) {
            if(arr[i] > time) {
                n --;
            } else {
                sum += arr[i];
            }
            if(sum >= time * n) {
                return true;
            }
        }
        return false;
    }
}
